// pages/wlkj/time/index.js
const app = getApp();
const db = wx.cloud.database();
const util=require('../../utils/util.js')
Page({
  data: {
    timer:0,
    times:0,          //计时（毫秒）
    minute: '0' + 0,   // 分
    second: '0' + 0,    // 秒
    millisecond: '0'+0  //毫秒
  },

//计时开始
  start: function () {
    var timer = this.data.timer;
    if(timer!=0){
     this.wxAlert('已经开始计时了！')
     return;
    }
    this.setInterval();
  },
  // 计时器
  setInterval: function () {
    var _this = this;
    var times = _this.data.times;
    _this.data.timer = setInterval(function () {  // 设置定时器
      times= times+96;
      _this.setData({times:times});
      _this.setViewTime();
    }, 96)
  },
 setViewTime:function(){
    var _this = this;
    let time = _this.data.times;
    let m = Math.floor(time / 1000 / 60);
    let s = Math.floor(time / 1000 % 60);
    let ms = Math.floor(time % 1000 /10 );

    //设置分
    if(m<10){
      m = '0'+m;
    }
    if(m != _this.data.minute){
      _this.setData({ minute:m})
    }
    //设置秒
    if(s<10){
      s = '0'+s;
    }
    if(s != _this.data.second){
      _this.setData({ second:s})
    }
    //设置毫秒
    if(ms<10){
      ms = '0'+ms;
    }
    _this.setData({ millisecond:ms })
 },

//暂停
  stop: function () {
    let _this = this;
    clearInterval(_this.data.timer);
    let m = _this.data.minute;
    let s = _this.data.second;
    let mi =_this.data.millisecond;
    let times = _this.data.times;
    let formattimes = m+'分'+s+'.'+mi+'秒';

    //清零
    _this.setData({
      timer:0,
      times:0,
      minute: '0' + 0,   // 分
      second: '0' + 0,    // 秒
      millisecond: '0'+0  //毫秒
    })

    if(times < 5*1000 ){
       _this.wxAlert('还不到5秒，来条士力架吧！') ;
       return
    }

    db.collection('sport').add({
      data:{  
        times:times,
        formattimes:formattimes,
        createtm:new Date(),
        createDate:util.formatDate(new Date()),
        createHours:util.formatHms(new Date())
      }
    })
    _this.wxAlert('您本次运动了 \r\n '+formattimes+' \r\n ！') 
  },

  //自定义alert
  wxAlert:function (content) {
    wx.showToast({
      title: content,
      icon: 'none',
      duration: 2000 
    })
  },

})